const dotenv = require('dotenv');
const OpenAI = require('openai');
const path = require('path');
const handleStream = require('./handleStream');
const handleNonStream = require('./handleNonStream');
const handleError = require('./handleError');

function registerAIQuery(app, baseUrl) {
    dotenv.config({ path: path.join(__dirname, '.env') });

    const openai = new OpenAI.OpenAI({
        apiKey: process.env.AI_API_KEY,
        baseURL: process.env.AI_SERVER_URL,
    });

    app.post(path.posix.join(baseUrl, '/queryAI'), async (req, res) => {
        try {
            if (!req.body.model) {
                req.body.model = process.env.AI_MODEL;
            }
            const response = await openai.chat.completions.create(req.body);

            if (req.body.stream) {
                await handleStream(response, res);
            } else {
                handleNonStream(response, res);
            }
        } catch (error) {
            console.log(error);
            handleError(error, res, req.body.stream);
        }
    });
}

module.exports = registerAIQuery;